package com.socool.sinofaith.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import com.socool.sinofaith.dao.QuestionAnswerDao;
import com.socool.sinofaith.dao.SifTaskDao;
import com.socool.sinofaith.model.QuestionAnswerBean;
import com.socool.sinofaith.model.SifTaskBean;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import net.tsz.afinal.http.AjaxParams;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class S {

	private static String format = "yyyy-MM-dd HH:mm:ss";
	private static SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINA);

	private S() {
	}

	public static class State {
		public static final int SUCCESS = 1;
		public static final int FAIL = 0;
	}

	public static void deleteTemp(final Activity act, final int days, final Handler handler) {
		final SQLiteDatabase db = new AndroidSQLiteOpenHelper(act).getWritableDatabase();
		final QuestionAnswerDao questionAnswerDao = new QuestionAnswerDao(act);
		Observable.just(days).subscribeOn(Schedulers.io()).map(new Func1<Integer, String>() {
			@Override
			public String call(Integer days) {
				final Calendar calendar = Calendar.getInstance();
				calendar.add(Calendar.DATE, days);
				return sdf.format(calendar.getTime());
			}
		}).flatMap(new Func1<String, Observable<SifTaskBean>>() {
			@Override
			public Observable<SifTaskBean> call(String date) {
				final String sql = "select * from Sif_Task where CreateTime < '" + date + "'";
				List<SifTaskBean> list = new SifTaskDao(act).queryBySql(sql);
				final String sql2 = "delete from Sif_Task where CreateTime < '" + date + "'";
				db.execSQL(sql2);
				return Observable.from(list);
			}
		}).doOnNext(new Action1<SifTaskBean>() {
			@Override
			public void call(SifTaskBean sifTask) {
				final String sql = "delete from Sif_SubTask where Task_ID = '" + sifTask.getTask_ID() + "'";
				db.execSQL(sql);
			}
		}).doOnNext(new Action1<SifTaskBean>() {
			@Override
			public void call(SifTaskBean sifTask) {
				final String sql = "delete from Sif_SubTemplate where Task_ID = '" + sifTask.getTask_ID() + "'";
				db.execSQL(sql);
			}
		}).doOnNext(new Action1<SifTaskBean>() {
			@Override
			public void call(SifTaskBean sifTask) {
				final String sql = "delete from Sif_TaskAddress where Task_ID = '" + sifTask.getTask_ID() + "'";
				db.execSQL(sql);
			}
		}).doOnNext(new Action1<SifTaskBean>() {
			@Override
			public void call(SifTaskBean sifTask) {
				final String sql = "delete from Sif_TaskQuestion where Task_ID = '" + sifTask.getTask_ID() + "'";
				db.execSQL(sql);
			}
		}).doOnNext(new Action1<SifTaskBean>() {
			@Override
			public void call(SifTaskBean sifTask) {
				final String sql = "delete from Sif_QuestionOptions where Task_ID = '" + sifTask.getTask_ID() + "'";
				db.execSQL(sql);
			}
		}).flatMap(new Func1<SifTaskBean, Observable<QuestionAnswerBean>>() {
			@Override
			public Observable<QuestionAnswerBean> call(SifTaskBean sifTask) {
				final String sql1 = "select * from QuestionAnswer where Task_ID = '" + sifTask.getTask_ID() + "'";
				final List<QuestionAnswerBean> list = questionAnswerDao.queryBySql(sql1);
				final String sql2 = "delete from QuestionAnswer where Task_ID = '" + sifTask.getTask_ID() + "'";
				db.execSQL(sql2);
				return Observable.from(list);
			}
		}).flatMap(new Func1<QuestionAnswerBean, Observable<String>>() {
			@Override
			public Observable<String> call(QuestionAnswerBean answer) {
				return Observable.from(answer.getAnswer().split("#"));
			}
		}).subscribe(new Subscriber<String>() {
			@Override
			public void onCompleted() {
				handler.sendEmptyMessage(State.SUCCESS);
			}

			@Override
			public void onError(Throwable throwable) {
				handler.sendEmptyMessage(State.FAIL);
			}

			@Override
			public void onNext(String path) {
				File file = new File(path);
				if (file.exists()) {
					file.delete();
				}
			}
		});
	}

	public static String getPath(String path) {
		File file = new File(path);
		if (!file.exists() || !file.isFile()) {
			return path;
		}
		String name = file.getName();
		String prefix = name.substring(name.lastIndexOf("."));
		String newName = String.valueOf(file.lastModified()) + prefix;
		return path.replaceAll(name, newName);
	}

	private static final Calendar cal = Calendar.getInstance();
	private static final SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);

	public static String getFileDate(File file) {
		long time = -1;
		try {
			String name = file.getName();
			time = Long.valueOf(name.substring(0, name.lastIndexOf(".")));
		} catch (Exception e) {
		}
		if (time < 0) {
			time = file.lastModified();
		}
		cal.setTimeInMillis(time);
		return formatter.format(cal.getTime());
	}

	public static void FileParams(final Context context, final AjaxParams params, final File file)
			throws FileNotFoundException {
		params.put("file", file);
		params.put("exposuretime", S.getFileDate(file));
		params.put("VerNum", getVersion(context));
	}

	private static String version = "";

	public static String getVersion(final Context context) {
		if (TextUtils.isEmpty(version)) {
			try {
				PackageManager manager = context.getPackageManager();
				PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
				version = info.versionName;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return version;
	}

	public static int getFileNum(final Activity act, String phone, String taskId, String subtaskId, String stempId) {
		int num = 0;
		final String sql = "select * from " + QuestionAnswerBean.TABLENAME + " where Submiter='" + phone + "'"
				+ " and IsFinish='1'" + (TextUtils.isEmpty(taskId) ? "" : (" and Task_ID='" + taskId + "'"))
				+ (TextUtils.isEmpty(subtaskId) ? "" : (" and SubTask_ID='" + subtaskId + "'"))
				+ (TextUtils.isEmpty(stempId) ? "" : (" and Stemp_ID='" + stempId + "'"));
		final QuestionAnswerDao answerDao = new QuestionAnswerDao(act);
		try {
			final ArrayList<QuestionAnswerBean> answers = answerDao.queryBySql(sql);
			for (QuestionAnswerBean answer : answers) {
				if (!TextUtils.isEmpty(answer.getFileCount()) && TextUtils.isDigitsOnly(answer.getFileCount())) {
					num += Integer.valueOf(answer.getFileCount());
				}
			}
		} catch (Exception e) {
			Log.e("getFileNum_sql", sql);
			Log.e("getFileNum_exception", e.getMessage());
		}
		return num;
	}
}
